<html>
	<head>
		<title>Calculator</title>
	</head>
	<body>
		<h1> CS 143: Calculator </h1>
		<h3>By Ben Phung (603-777-189)</h3>
		<p>
			<form action="calculator.php" method="GET">
				Input expression to be calculated:<br>
				<input type="text" name="expr"/>
				<input type="submit" value="Calculate"/>
			</form>
		</p>
		<?php
			if ($_GET["expr"]) {
				$expr = $_GET["expr"];
				echo "<h2> Result </h2>";

				// Remove all blank spaces
				$newExpr = preg_replace("/[ ]+/i", "", $expr);

				// Replace double negatives with positive
				$newExpr = preg_replace("/\-\-/i", "+", $newExpr);
				$newExpr = preg_replace("/[\+]+/i", "+", $newExpr);

				// Check for invalid characters
				if (preg_match('/[^0-9\/*\-+.]+/', $newExpr)) {
					echo "Invalid input expression " . $expr . ".";
				} else {
					// Supress error reporting for cases such as 0/0
					// Evaluate and output answer
					@eval("\$ans = $newExpr ;");
					echo $expr . " = " . $ans;
				}
			}
		?>
	</body>
</html>
